package net.aiion.weave.util.cryptography;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES
{
    public AES() {
    }

    public String generateKey() throws IOException {
        try {
            final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            final SecretKey secretKey = keyGenerator.generateKey();
            return HexadecimalConverter.convertBytesToHexString(secretKey.getEncoded());
        } catch (NoSuchAlgorithmException ex) {
            throw new IOException(ex);
        }
    }

    public String encryptString(final String aMessage, final String aSecretKey) throws IOException {
        try {
            final SecretKey secretKey = createSecretKey(aSecretKey);
            final Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return HexadecimalConverter.convertBytesToHexString(cipher.doFinal(aMessage.getBytes()));
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }

    public String decryptString(final String aCipher, final String aSecretKey) throws IOException {
        try {
            final SecretKey secretKey = createSecretKey(aSecretKey);
            final Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(HexadecimalConverter.convertHexStringToBytes(aCipher)));
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }

    private SecretKey createSecretKey(final String aSecretKey) {
        return new SecretKeySpec(HexadecimalConverter.convertHexStringToBytes(aSecretKey), "AES");
    }
}
